<template>
  <view class="content">
    <svg xmlns="http://www.w3.org/2000/svg" version="1.1" class="svg" :style="`stroke-dasharray: ${dasharray};stroke-dashoffset:${dashoffset};`">
      <polyline ref="line" points="0,40 40,40 40,80 80,80 80,120 120,120 120,160" style="fill:white;stroke:red;stroke-width:4" />
    </svg>
    <view class="color-box" :style="`animation-delay: ${delay}s;`"></view>
    <view style="width: 100%;">
      <view class="div" :style="`--animation-delay: ${delay}s;`"></view>
      <slider @changing="sliderChange" show-value />
    </view>
    <view>拖动滑块后绿色小方块将跟着移动，并且svg图形将开始绘制</view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
const line = ref<SVGPolylineElement>()
const delay = ref(0)
const dasharray = ref(0)
const dashoffset = ref(0)
const sliderChange = (e: any) => {
  // 当动画的延迟是一个负数时，可以理解为动画在过去的时间点已开始播放，比如-2s代表动画已经播放到了2秒的状态
  delay.value = -(e.detail.value/100*6)

  /**
   * 利用stroke-dasharray样式使得svg以虚线填充，而填充数值刚好是svg的路径长度，
   * stroke-dashoffset控制填充的偏移，初始获取到路径长度后，设置偏移量为路径长度，则svg刚好是空白的，
   * 当偏移量趋近于0，svg逐渐被填满从而显示出完整图形
   */
  dashoffset.value = dasharray.value - e.detail.value/100 * dasharray.value
}
onMounted(() => {
  dasharray.value = line.value?.getTotalLength() || 0
  dashoffset.value = dasharray.value
})
</script>

<style>
.div {
  width: 50rpx;
  height: 50rpx;
  background-color: #42b983;
  border-radius: 4rpx;
  animation: move 6s linear;
  animation-fill-mode: forwards;
  animation-play-state: paused;
  animation-delay: var(--animation-delay);
  margin-bottom: 100rpx;
}
.color-box {
  width: 100%;
  height: 100rpx;
  background-color: #f38181;
  animation: color-change 6s linear;
  animation-fill-mode: forwards;
  animation-play-state: paused;
}
@keyframes move {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(700rpx);
  }
}
@keyframes color-change {
  0% {
    background-color: #f38181;
  }
  100% {
    background-color: #30e3ca;
  }
}
</style>
